package common.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import model.Material;

import common.view.IndentView;

import implementor.IndentImpl;
import implementor.IndentItemsImpl;
import implementor.StockInImplementor;
import dao.IndentItemsDao;
import dao.IndentsDao;
import dao.StockInDao;
import dbhandelling.Connections;
import dto.IndentItems;
import dto.Indents;
import dto.MaterialSpecification;
import utility.AppUtilities;
import utility.Constants;
import utility.Validater;
import utility.ViewUtilities;


public class IndentController implements ActionListener{
	private IndentView view;
    private Indents model;
    private MaterialAdderController controller;
    private static int srNo=1;
    private Vector<IndentItems>indentItems;
	// CONSTRUCTOR
	
	
	/**
	 * Adds the material object in table , a utility method candidate.With help of this
	 * material object please make Indent object.i'e initialize the model.
	 * @throws Exception 
	 */
	
    public IndentController(IndentView view,Indents model) throws Exception
    {
    	this.view=view;
    	this.model=model;
    	view.actionlisterners(this);
    	indentItems=new Vector<IndentItems>();
    	controller = new MaterialAdderController(view.getmAdder(),null);
    	view.getmAdder().getBtnAdd().addActionListener(this);
    	AppUtilities.fillProjectNameCombo(view.getCbProject());
    }
    
    
    
    public void addInTable() throws SQLException
	{
	   Material material = controller.getModel();
	   IndentItems i = new IndentItems();
	   i.setModelMaterial(material);
	   int requiredQty= Integer.parseInt(view.getTfRequiredQty().getText().trim());
	   i.setRequiredQty(requiredQty);
	   i.setmCode(material.getMCode());
	   i.setSpecCode(material.getCurrentSpecs().getAutoSpecCode());
	   i.setindentId(Integer.parseInt(view.getTfIndentNo().getText()));
	   
	   StockInDao sDao=new StockInImplementor();
	   double remainingQty=sDao.getStockQty(material.getMCode(), material.getCurrentSpecs().getAutoSpecCode());
	   i.setmodelRemainingQty(remainingQty);
	   
	   DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
	   Material tempm=i.getModelMaterial();
	   MaterialSpecification specs= i.getModelMaterial().getCurrentSpecs();
	   
	   dm.addRow(new Object[]{srNo++,tempm.getMCode(),tempm.getMname(),specs.getmSpecs(),tempm.getUnit(),i.getRequiredQty(),
			                  i.getmodelRemainingQty()});
	   
	   indentItems.add(i);
	}
    
    
    
	
	/**
	 * Called when save button is called.Should save the data in Indent and Indent Item tabels
	 * @throws Exception 
	 */
	
	private  void reactToSave() throws Exception
	{
		
		Connection con =Connections.getMyConnection();
		try {
			con.setAutoCommit(false);
			int indentId= this.saveToIndent();
			this.saveToIndentItems(indentId);
		} catch (Exception e) {
			con.rollback();
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		con.commit();
		con.setAutoCommit(true);
		
		
	}
	
	private int saveToIndent() throws Exception
	{
		IndentsDao inDao=new IndentImpl();
		Indents i=new Indents();
		i.setGeneratedId(AppUtilities.getGeneratedById(view.getTfGenratedBy().getText()));
		i.setGenerationDate(ViewUtilities.convert(view.getTfGeneratedDate().getText()));
		i.setProjectId(AppUtilities.getProjectId(view.getCbProject().getSelectedItem().toString()));
		i.setState(Constants.CREATED);
		i.setVersion(1);
		System.out.println("the date is "+i.getGenerationDate());
		inDao.add(i);
		int autoId= inDao.getAutoId();
		
		return autoId;
		
	}
	
	
	private void saveToIndentItems(int autoIndentId) throws  Exception
	{
	   
		int i =0;
		for(;i<this.indentItems.size();i++)
			this.indentItems.get(i).setindentId(autoIndentId);
		
		IndentItemsDao indentItemsDao = new IndentItemsImpl();
		for(i=0;i<indentItems.size();i++)
			indentItemsDao.add(this.indentItems.get(i));
	   
	}
	
	private void delete(int row)
	{
		JTable table=view.getTable();
		DefaultTableModel dm = (DefaultTableModel) table.getModel();
		dm.removeRow(row);
		indentItems.remove(row);
	}



	@Override
	public void actionPerformed(ActionEvent arg0) {
		String k=arg0.getActionCommand();
		   if(k.equals("GeneratedDate"))
		   {
			   ViewUtilities.makeDateComponent(view.getTfGeneratedDate());
		   }
		  
		   if(k.equals("Save"))
		   {
			   try {
					Validater val = new Validater(view);
					//String message = val.validateForEmpty();
					//if(message.equals(""))
					{
					  reactToSave();
					JOptionPane.showMessageDialog(null,"Successfully Saved!");
					//val.refresh();
					}
				
					//else
						//JOptionPane.showMessageDialog(null,message);
					
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null,"Failed To Save!");
					e1.printStackTrace();
				}
		   }
			
		   if(k.equals("mAdderAdd"))
			{
				 controller.changeModel();
				try {
					this.addInTable();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		   
		   if(k.equals("btnDate"))
		   {
			   ViewUtilities.makeDateComponent(view.getTfGeneratedDate());
		   }
		
	}
	
	
	
	//******************************DYNAMIC PART*******************************************************//
	
}
